class Snake {
  // 获取蛇的容器
  element: HTMLElement
  // 表示蛇头的元素
  head: HTMLElement
  // 获取蛇的身体
  bodies: HTMLCollection
  constructor() {
    this.head = document.querySelector('#snake>div') as HTMLElement
    this.element = document.getElementById('snake')!
    this.bodies = this.element.getElementsByTagName('div')
  }
  //获取X轴坐标
  get X() {
    return this.head.offsetLeft
  }
  // 获取Y轴坐标
  get Y() {
    return this.head.offsetTop
  }
  set X(value: number) {
    // 值不发生变化就不修改
    if (this.X == value) {
      return
    }
    if (value < 0 || value > 290) {
      // 蛇触边了
      throw new Error('蛇撞墙了')
    }
    if (
      this.bodies[1] &&
      (this.bodies[1] as HTMLElement).offsetLeft === value
    ) {
      if (value > this.X) {
        value = this.X - 10
      } else {
        value = this.X + 10
      }
    }
    // 移动身体
    this.moveBody()
    this.head.style.left = value + 'px'
    this.checkHeadBody(this.X, this.Y)
  }
  set Y(value: number) {
    // 值不发生变化就不修改
    if (this.Y == value) {
      return
    }
    if (value < 0 || value > 290) {
      // 蛇触边了
      throw new Error('蛇撞墙了')
    }
    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
      if (value > this.Y) {
        value = this.Y - 10
      } else {
        value = this.Y + 10
      }
    }
    // 移动身体
    this.moveBody()
    this.head.style.top = value + 'px'
    this.checkHeadBody(this.X, this.Y)
  }
  // 蛇增加身体的方法
  addBody() {
    this.element.insertAdjacentHTML('beforeend', '<div></div>')
  }
  // 蛇身体移动
  moveBody() {
    for (let i = this.bodies.length - 1; i > 0; i--) {
      let X: number = (this.bodies[i - 1] as HTMLElement).offsetLeft
      let Y: number = (this.bodies[i - 1] as HTMLElement).offsetTop
      ;(this.bodies[i] as HTMLElement).style.left = X + 'px'
      ;(this.bodies[i] as HTMLElement).style.top = Y + 'px'
    }
  }
  // 检查蛇是否撞到自己
  checkHeadBody(x: number, y: number) {
    for (let i = 1; i < this.bodies.length; i++) {
      let X: number = (this.bodies[i] as HTMLElement).offsetLeft
      let Y: number = (this.bodies[i] as HTMLElement).offsetTop
      if (X == x && Y == y) {
        throw new Error('蛇撞到自己了')
      }
    }
  }
}
export default Snake
